<?php

namespace Doc\Controller;

use Common\Controller\BaseController;
use Common\Model\ArticleModel;
use Common\Model\CateModel;
use Common\Model\ClassModel;
use Common\Model\DocCountModel;
use Common\Model\DocModel;
use Common\Model\BbsDocModel;
use Common\Model\BbsModel;
use Common\Model\UserDocModel;
use Common\Model\UserOrgModel;
use Common\Model\UserModel;
use Common\Model\UserPDocModel;

class DocController extends BaseController {

    /**
     * 展示文档的详细信息
     */
    public function show(){
        $did = I('get.did', 0);
        $doc = DocModel::getDocById($did);
        if(!$doc){
            $this->error('数据异常，请稍后再试！');
        };
        $login = false;     // 是否登陆
        $manager = false;   // 是否是管理员
        $super = false;     // 是否是团体的超级管理员或私有文档的拥有者
        $owner = false;
        $collect = false;   // 是否收藏
        if(UID){
            $login = true;
            $manager = UserDocModel::checkManager(UID, $doc);
            $super = UserDocModel::checkManager(UID, $doc, true);
            $owner = $doc['bid'] ? false : UID == $doc['uid'];
            $collect = UserDocModel::checkCollected(UID, $did);
        }
        $canRead = $doc['status'] == DocModel::NORMAL || ($doc['status'] == DocModel::HIDDEN && $manager);
        $canFocus = $login && !$owner;
        $canEdit = $doc['status'] != DocModel::DELTEL && $super;
        $article = ArticleModel::getCurArticle($did, ArticleModel::MOREN_CATE);
        DocCountModel::update($did, 'visit');
        $this->assign('collect', $collect);
        $this->assign('canRead', $canRead);
        $this->assign('canFocus', $canFocus);
        $this->assign('canEdit', $canEdit);
        $this->assign('super', $super);
        $this->assign('doc', $doc);
        $this->assign('article', $article);
        $this->assign('title', $doc['name'].' - 文档主页');
        $this->assign('description', '文档'.$doc['name'].'的首页面，展示文档的基本信息、前言简介、目录内容以及其他相关信息!'.$doc['desc']);
        $this->display();
    }

    /**
     * Ajax收藏文档与取消收藏文档
     * 接收到的type为1表示收藏，为2表示取消收藏
     */
    public function ajaxfocus(){
        $did = I('post.did', 0);
        $type = I('post.type', 0);      // 为1表示收藏，为2表示取消收藏
        if(!UID){
            json(400, '您需要登陆之后才能进行操作');
        }
        if(!$did || !$type){
            json(400, '数据异常，请刷新后再试！');
        }
        $user = $this->user;
        $doc = DocModel::getDocById($did);
        if(!$user || !$doc){
            json(400, '数据异常，请稍候再试！');
        }
        $bCollect = UserDocModel::checkCollected(UID, $did);
        if($type == 1){     // 表示收藏文档
            if($bCollect){
                json(400, '您已经收藏过该文档，请勿重复收藏！');
            }
            if($user['gx'] < 1){
                json(400, '收藏文档需要花费1贡献度，您的贡献度不足！');
            }
            $result = UserDocModel::collect(UID, $doc);
            if(!$result){
                json(400, '收藏文档失败，请稍后再试！');
            }
            json(200);
        }else if($type == 2){
            if(!$bCollect){
                json(400, '您还未收藏该文档！');
            }
            $res = UserDocModel::cancelCollect(UID, $did);
            if(!$res){
                json(400, '取消收藏文档失败，请稍后再试！');
            }
            json(200);
        }else{
            json(400,'收藏系统出现异常,请您稍候再试！');
        }
    }

    /**
     * Ajax获取文档的目录内容
     */
    public function ajaxcate(){
        $did = I('post.did', 0);
        if(!$did){
            json(400);
        }
        $cate = CateModel::getCateById($did);
        if($cate['content']){
            json(200, '', [
                'content' => $cate['content'],
                'time' => date('Y-m-d H:i:s', $cate['create'])
            ]);
        }else{
            json(401);
        }
    }

    /**
     * 用户捐赠文档
     */
    public function donation(){
        if(!UID){
            json(204, '登陆后再进行操作');
        }
        $did = I('get.did', 0);
        $gx = I('post.gx', 0);
        $user = $this->user;
        $doc = DocModel::getDocById($did);
        if(!$doc || !$gx || !$user){
            json(204, '数据异常，请稍后再试');
        }
        if ($user['gx'] < $gx) {
            json(204, '您的贡献度不足');
        }
        if(UserDocModel::donation(UID, $doc, $gx)){
            json(200, '感谢您的捐赠，愿你每天好心情');
        }
        json(204, '捐赠失败，请稍后再试');
    }

    /**
     * 设置、修改文档的相关信息
     */
    public function set(){
        if(!UID){
            $this->error('您需要先登录账号！', U('/login@wooo.wang'));
        }
        $did = I('get.did', 0);
        $doc = DocModel::getDocById($did);
        if(!$doc){
            $this->error('文档数据异常，请稍后再试！');
        }
        if(!UserDocModel::checkManager(UID, $doc, true)){
            $this->error('您没有操作权限');
        }
        if(IS_POST){
            $img = I('post.img', '');
            $name = I('post.name', '');
            $desc = I('post.desc', '');
            $cate = I('post.cateid', 0);
            $needReview = I('post.need_review', -2);
            $canEdit = I('post.can_edit', -2);
            if(!$img || !checkStrLength($name, 2) || !$desc || !$cate
                || !in_array($needReview, [DocModel::NEED_REVIEW, DocModel::NEEDNOT_REVIEW])
                || !in_array($canEdit, [DocModel::CAN_EDIT, DocModel::CANNOT_EDIT])){
                $this->error('您提交的文档数据有误，请您重新提交！');
            }
            $data = [
                'img' => $img,
                'name' => $name,
                'desc' => $desc,
                'cate' => $cate,
                'can_edit' => $canEdit,
                'need_review' => $needReview
            ];
            if(!DocModel::update($did, $data)){
                $this->error('文档修改出现异常，请稍后再试！');
            }
            $this->success('文档修改成功！', U('/show/'.$did));
        }else{
            $this->assign('cate', ClassModel::getCreateClass());
            $this->assign('doc', $doc);
            $this->assign('token', qiniu());
            $this->assign('title', $doc['name'].' - 设置文档' );
            $this->assign('description', '设置修改'.$doc['name'].'文档的相关信息，'.$doc['desc']);
            $this->display();
        }
    }

    /**
     * 隐藏与显示文档
     */
    public function hide()
    {
        if(!UID){
            $this->error('您需要先登录账号！', U('/login@wooo.wang'));
        }
        $did = I('get.did', 0);
        $doc = DocModel::getDocById($did);
        if(!$doc){
            $this->error('文档数据异常，请稍后再试！');
        }
        if(!UserDocModel::checkManager(UID, $doc, true)){
            $this->error('您没有操作权限');
        }
        if(IS_POST){
            $status = I('post.status', -2);
            if (!in_array($status, [DocModel::NORMAL, DocModel::HIDDEN])) {
                $this->error('参数错误，请刷新后再试');
            }
            if($status == DocModel::HIDDEN){
                if($doc['status'] == DocModel::HIDDEN){
                    $this->error('您的文档已被隐藏，请勿重复操作！');
                }else{
                    if(DocModel::updateStatus($doc, DocModel::HIDDEN)){
                        $this->success('您已成功隐藏「 '.$doc['name'].'」文档！');
                    }else{
                        $this->error('隐藏文档失败，请您刷新后再试！');
                    }
                }
            }else{
                if($doc['status'] == DocModel::NORMAL){
                    $this->error('您的文档已取消隐藏，请勿重复操作！');
                }else{
                    if(DocModel::updateStatus($doc, DocModel::NORMAL)){
                        $this->success('您已成功取消隐藏「 '.$doc['name'].'」文档！');
                    }else{
                        $this->error('取消隐藏文档失败，请您刷新后再试！');
                    }
                }
            }
        }else{
            $this->assign('doc', $doc);
            $this->assign('title', $doc['name'].' -'.($doc['status'] == DocModel::NORMAL ? '隐藏' : '取消隐藏').'文档');
            $this->assign('description','隐藏与取消隐藏'.$doc['name'].'文档，文档隐藏后文档将不能被浏览，但可以被管理员编辑！');
            $this->display();
        }
    }

    /**
     * 冻结文档
     */
    public function freeze(){
        if(!UID){
            $this->error('您需要先登录账号！', U('/login@wooo.wang'));
        }
        $did = I('get.did', 0);
        $doc = DocModel::getDocById($did);
        if(!$doc){
            $this->error('文档数据异常，请稍后再试！');
        }
        if(!UserDocModel::checkManager(UID, $doc, true)){
            $this->error('您没有操作权限');
        }
        if(IS_POST){
            $status = I('post.status', -2);
            if (!in_array($status, [DocModel::NORMAL, DocModel::DELTEL])) {
                $this->error('参数错误，请刷新后再试');
            }
            if($status == DocModel::DELTEL){
                if($doc['status'] == DocModel::DELTEL){
                    $this->error('您的文档已被冻结，请勿重复操作！');
                }else{
                    if(DocModel::updateStatus($doc, DocModel::DELTEL)){
                        $this->success('您已成功冻结「 '.$doc['name'].'」文档！');
                    }else{
                        $this->error('冻结文档失败，请您刷新后再试！');
                    }
                }
            }else{
                if ($doc['bid']) {
                    $docNum = BbsDocModel::getBbsDocsCount($doc['bid'], 2);
                    $needgx = $docNum >= 3 ? 1000 : pow(10, $docNum);
                    $bbs = BbsModel::getBbsById($doc['bid'], false);
                    if($bbs['gx'] < $needgx){
                        $this->error('您的团体的贡献度不足，无法解冻该文档！');
                    }
                } else {
                    $docNum = UserPDocModel::getUserPDocsCount(UID, UserPDocModel::NORMAL_HIDE);
                    $needgx = $docNum >= 3 ? 1000 : pow(10, $docNum);
                    if($this->user['gx'] < $needgx){
                        $this->error('您的贡献度不足，无法解冻该文档！');
                    }
                }
                if(DocModel::recoverDoc($doc, $needgx)){
                    $this->success('您已成功解冻该文档！', U('/freeze/'.$did));
                }
                $this->error('解冻文档失败，请刷新后再试！');
            }
        }else{
            if($doc['status'] == DocModel::DELTEL){   // 解冻文档
                if ($doc['bid']) {
                    $count = BbsDocModel::getBbsDocsCount($doc['bid'], 2);
                } else {
                    $count = UserPDocModel::getUserPDocsCount(UID, UserPDocModel::NORMAL_HIDE);  // 当前正常状态下的私有文档数量
                }
                $this->assign('needgx', $count >= 3 ? 1000 : pow(10, $count));
            }
            $this->assign('doc', $doc);
            $this->assign('title', $doc['name'].' -'.($doc['status'] == DocModel::NORMAL ? '冻结' : '解冻').'文档');
            $this->assign('description','冻结与解冻'.$doc['name'].'文档，文档冻结后将不能编辑不能浏览，解冻文档后可继续编辑浏览！');
            $this->display();
        }
    }

    /**
     * 超级管理员编辑文档
     */
    public function edit(){
        if(isMobile()){
            $this->error('抱歉，暂不支持移动端进行文档编辑');
        }
        if(!UID){
            $this->error('您需要先登录账号！', U('/login@wooo.wang'));
        }
        $did = I('get.did', 0);  // doc id
        $cid = I('get.cid', 0);  // cate id
        $doc = DocModel::getDocById($did);
        if(!$doc){
            $this->error('数据异常，请刷新后再试！');
        }
        if (!UserDocModel::checkEditAuth(UID, $doc)) {
            $this->error('Sorry，您当前没有编辑权限！');
        }
        $super = 0;
        $needreview = true;
        $cate = CateModel::getCateById($did);
        if (UserDocModel::checkManager(UID, $doc, true)) {
            $super = 1;
            if ($doc['need_review'] == DocModel::NEEDNOT_REVIEW) $needreview = false;
            $this->assign('cate', $cate);
        }else{
            $this->assign('articleTitle', CateModel::getTitleByCid($cate, $cid));
        }
        if(IS_POST){
            $title = I('post.title', '');
            $md = I('post.md', '');
            $html = isset($_POST['html']) ? $_POST['html'] : '';
            $desc = I('post.desc', '');
            if(!$title || !$md || !$desc){
                $this->error('数据，请您稍后再试！');
            }
            $data = [
                'did' => $did,
                'cid' => $cid,
                'title' => $title,
                'desc' => $desc,
                'md' => $md,
                'uid' => UID,
                'create' => time()
            ];
            if (!$needreview) {
                $data['html'] = filterXss($html);
                $data['update'] = time();
                $data['mid'] = UID;
                $data['status'] = ArticleModel::REVIEWED_YES;
            }
            $aid = ArticleModel::createArticle($data);
            if(false === $aid){
                $this->error('文档提交失败，请稍后再试！');
            }
            if ($needreview) {
                $this->success('您的编辑已成功提交，请您静待管理员的审核！', U('/'.$did.'/c/'.$cid));
            } else {
                $this->success('您的编辑已成功提交并已更新文档！', U('/'.$did.'/c/'.$cid));
            }
        }else{
            $article = ArticleModel::getCurArticle($did, $cid);
            $this->assign('doc', $doc);
            $this->assign('super', $super);
            $this->assign('needreview', $needreview);
            $this->assign('md', $article['md']);
            $this->assign('cid', $cid);
            $this->assign('token', qiniu());
            $this->assign('title', 'Editor - Doc');
            $this->assign('description', '我网的文档编辑器，支持Markdown，能够实时预览，用户可以通过编辑器来进行编辑！');
            $this->display();
        }
    }

    /**
     * 超级管理员更新文档目录
     */
    public function updatecate(){
        $did = I('post.did', 0);
        $content = isset($_POST['data']) ? $_POST['data'] : '';
        $count = I('post.count', 0);
        if(!$did || !$content || !$count ||!UID){
            json(400);
        }
        $doc = DocModel::getDocById($did, false);
        if(!$doc || !UserDocModel::checkManager(UID, $doc, true)){
            json(400);
        }
        $data = [
            'did' => $did,
            'content' => $content,
            'count' => $count,
            'aid' => UID,
            'create' => time()
        ];
        if(CateModel::addData($data)){
            json(200);
        }
        json(400);
    }

    /**
     * 管理员审核文档
     */
    public function review(){
        if(isMobile()){
            $this->error('抱歉，暂不支持移动端审阅文档');
        }
        $aid = I('get.aid', 0);  // cate id
        $article = null;
        if(!$aid || !($article = ArticleModel::getArticleById($aid))){
            $this->error('文档数据异常，请刷新后再试！');
        }
        $doc = DocModel::getDocById($article['did']);
        $manager = UID ? UserDocModel::checkManager(UID, $doc) : false;
        if(IS_POST){
            if(!$manager){
                $this->error('您没有操作权限');
            }
            $result = I('post.result', 0);
            $desc = I('post.desc', '');
            if(!$result || !$desc){
                $this->error('参数异常');
            }
            $md = I('post.md', '');
            $html = $result == 1 ? $_POST['html'] : '';
            $data = array(
                'reply' => $desc,
                'html' => $html ? filterXss($html) : '',
                'mid' => UID,
                'status' => $result == 1 ? ArticleModel::REVIEWED_YES : ArticleModel::REVIEWED_NO,
                'update' => time()
            );
            if($md){
                $data['md'] = $md;
            }
            $res = ArticleModel::update($article, $data);
            if(!$res){
                $this->error('文档审阅异常，请刷新后再试');
            }
            $this->success('您已成功提交审阅结果！', $doc['bid'] ? U('/'.$doc['bid'].'/review/'.$doc['id'].'@bbs.wooo.wang') : U('/u/'.$doc['uid'].'/review/'.$doc['id'].'@wooo.wang'));
        }else{
            $base = ArticleModel::getCurArticle($article['did'], $article['cid']);
            $this->assign('doc', $doc);
            $this->assign('article', $article);
            $this->assign('author', UserModel::getUserById($article['uid'], false));
            $this->assign('token', qiniu());
            $this->assign('base', $base['md']);
            $this->assign('manager', $manager);
            $this->assign('title', $doc['name'].':'.$article['title'].' - 文档审阅');
            $this->assign('description', '团体管理员审阅用户编辑的'.$doc['name'].'文档的'.$article['title'].'文章，审阅通过即会更新文档到最新状态！');
            $this->display();
        }
    }

    /**
     * 展示文档具体内容
     */
    public function index(){
        $did = I('get.did', 0);
        $cid = I('get.cid', 0);
        $doc = DocModel::getDocById($did);
        if(!$doc){
            $this->error('文档数据异常，请稍后再试');
        }
        $cate = CateModel::getCateById($did);
        $this->assign('cid', $cid);     // 如果article不存在，使用$article['cid']会出错
        $this->assign('doc', $doc);
        $this->assign('cate', $cate['content']);
        $article = ArticleModel::getCurArticle($did, $cid);
        $article['author'] = UserModel::getUserById($article['uid'], false)['nick'];
        $this->assign('article', $article);
        $this->assign('token', qiniu());
        if($article['title']){
            $title = $doc['name'].'：'.$article['title'];
            $desc = '文档'.$doc['name'].'的'.$article['title'].'章节：'.mb_substr(strip_tags($article['html']), 0, 140, 'utf-8').'...';
        }else{
            $title = $doc['name'].'：'.$cid.'号章节';
            $desc = '文档'.$doc['name'].'的'.$cid.'号章节，该章节内容暂未编辑，请浏览其他章节！'.$doc['desc'];
        }
        $this->assign('title', $title);
        $this->assign('description', $desc);
        $this->display();

    }

























    /**
     * 暂时弃用
     */
//    public function history(){
//        $bid=I('get.b',0);
//        $cid=I('get.c',0);
//        $p=I('get.p',1);    //page count
//        $pcount=20;
//        if($bid){
//            $book=M('Book')->where(array('id'=>$bid,'status'=>1))->field('id,name,show,creator')->find();
//            if($book){
//                if($book['show']||$book['creator']==UID){
//                    $cate=M('Category')->where(array('book'=>$book['id']))->field('count,content')->order(array('create'=>'desc'))->find();
//                    $count=M('Article')->where(array('book'=>$bid,'cid'=>$cid))->count();
//                    $Page = new \Think\Page($count,$pcount);
//                    $list=M()->table(array('wo_article'=>'a','wo_user'=>'u'))->where(array('a.book'=>$book['id'],'a.cid'=>$cid))->where('a.author=u.id')->field('a.cid,a.desc,a.create,a.author,u.nick')->order(array('create'=>'desc'))->page($p.','.$pcount)->select();
//                    $this->assign('cate',$cate);
//                    $this->assign('book',$book);
//                    $this->assign('list',$list);
//                    $this->assign('page',$Page?$Page->show():null);
//                    $this->assign('count',$count?$count:0);
//                    $this->assign('cid',$cid);
//                    $this->assign('title','文档修改历史');
//                    $this->assign('description','一份文档必须经过千锤百炼才能成为真正的财富！');
//                    $this->display();
//                }else{
//                    $this->error('抱歉，您没有该文档历史版本的访问权限！');
//                }
//            }else{
//                $this->error('抱歉，您所查看的文档暂不存在或已被冻结！');
//            }
//        }else{
//            $this->error('抱歉，您所查看的文档暂不存在！');
//        }
//    }
}